import { HashService } from '@app/hash';
import { Injectable } from '@nestjs/common';
import { createReadStream, existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
import { join } from 'path';
import { cwd } from 'process';
import * as moment from "moment"

@Injectable()
export class FileService {

    constructor(
        private readonly hashService: HashService
    ) { }
    public static readonly Root = cwd();
    public static getSSLKey() {
        return readFileSync(join(this.Root, "keys", "api.bugwozi.top.key"))
    }
    public static getSSLPem() {
        return readFileSync(join(this.Root, "keys", "api.bugwozi.top.pem"))
    }
    private readonly Assets = join(FileService.Root, "assets")
    private readonly GoodsAvatarDir = join(this.Assets, "avatar", "goods")
    private readonly ShopAvatarDir = join(this.Assets, "avatar", "shop")
    public getGoodsAvatar(hash_key: string) {
        return join(this.GoodsAvatarDir, hash_key, "avatar.jpg")
    }
    public getShopAvatar(hash_key: string): string {
        return join(this.ShopAvatarDir, hash_key, "avatar.jpg")
    }

    public deepMkdir(path: string) {
        if (existsSync(path)) return
        const before = join(path, "..");
        if (!existsSync(before)) this.deepMkdir(before);
        mkdirSync(path);
    }

    public fileW2R(path: string, data: any = null) {
        if (!!data) {
            const beforePath = join(path, "..");
            if (!existsSync(beforePath)) this.deepMkdir(beforePath)
            writeFileSync(path, data);
            return null;
        }
        if (existsSync(path)) return createReadStream(path);
        return null;
    }
}
